<template>
  <div class="sms-login">
    <el-form ref="form" :model="form" :rules="rules" @submit.native.prevent="handleSubmit">
      <el-form-item prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      
      <el-form-item prop="code" class="code-input">
        <el-input v-model="form.code" placeholder="请输入验证码" />
        <el-button 
          type="primary" 
          :disabled="countdown > 0"
          @click="sendCode">
          {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { sendSmsCode, smsLogin } from '@/api/login'

export default {
  data() {
    return {
      form: {
        phone: '',
        code: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      loading: false,
      countdown: 0
    }
  },
  methods: {
    async sendCode() {
      try {
        await this.$refs.form.validateField('phone')
        await sendSmsCode(this.form.phone)
        this.startCountdown()
        this.$message.success('验证码已发送')
      } catch (error) {
        console.error(error)
      }
    },
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    async handleSubmit() {
      try {
        this.loading = true
        await this.$refs.form.validate()
        const token = await smsLogin(this.form)
        this.$store.dispatch('user/login', token)
        this.$router.push('/')
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.code-input {
  display: flex;
}
.code-input .el-input {
  flex: 1;
  margin-right: 10px;
}
</style>